package jp.co.redfox.archclub.poker;

import java.util.Scanner;

public class Question {
    private Scanner sc;
    private String question;
    private String answerType;
    private String[] answers;
    private String answerRegex;
    private Type type;

    public enum Type {
        plain, selectable;
    }

    /**
     * Constructor.
     * 
     * @param question
     *            asking question (Do you want to continue ?)
     * @param answerType
     *            answer type (y/n 1...10 etc)
     * @param answers
     *            acceptable answers (y,n 1,2,3 etc)
     */
    public Question(Type type, String question, String answerType, String... answers) {
        if (type == null) throw new IllegalArgumentException("type cannot be allowed null");
        this.question = question;
        this.answerType = answerType;
        this.answers = answers;
        this.type = type;
    }

    /**
     * Constructor.
     * 
     * @param question
     *            asking question (Do you want to continue ?)
     * @param answerRegex
     *            acceptable answer format as regular expressions
     * @param promptMessage
     *            When user mistake input, this message will prompt.
     */
    public Question(Type type, String question, String answerRegex, String promptMessage) {
        if (type == null) throw new IllegalArgumentException("type cannot be allowed null");
        this.question = question;
        this.answerRegex = answerRegex;
        this.type = type;
    }

    public String ask() {
        if (type == Type.plain)
            return askAsPlain();
        else if (type == Type.selectable)
            return askAsSelectable();
        else
            throw new IllegalStateException("Cannot ask your question.");
    }

    /**
     * asking question
     * 
     * @return user's answer
     */
    private String askAsPlain() {
        System.out.println(question);
        sc = new Scanner(System.in);
        String res = sc.nextLine();
        while (true) {
            if (res.matches(answerRegex))
                return res;
            System.out.println(answerType + "の形式で入力して下さい。");
            System.out.println(question);
            res = sc.nextLine();
        }
    }

    /**
     * asking question
     * 
     * @return user's answer
     */
    public String askAsSelectable() {
        System.out.println(question + answerType);
        sc = new Scanner(System.in);
        String res = sc.nextLine();
        while (true) {
            for (String answer : answers) {
                if (answer.equals(res))
                    return res;
            }
            System.out.println(answerType + "の形式で入力して下さい。");
            System.out.println(question + answerType);
            res = sc.nextLine();
        }
    }
}
